﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using ButsaScraperLib;

namespace ForecastManager.Dialogs
{
	/// <summary>
	/// Interaction logic for LoadForecastDialog.xaml
	/// </summary>
	public partial class LoadForecastDialog : Window
	{
		private List<ForecastPairRef> _forecastPairRefs = new List<ForecastPairRef>();

		private List<Team> _teams = new List<Team>();

		public Snapshot Snapshot;

		public LoadForecastDialog()
		{
			InitializeComponent();
		}

		/// <summary>
		/// Начало загрузки прогноза.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void LoadButtonClick(object sender, RoutedEventArgs e)
		{
			if (Snapshot == null)
			{
				if (SnapshotNameTextBox.Text.Trim() != String.Empty)
				{
					//загрузка снимка
					SnapshotNameTextBox.IsEnabled = false;
					LoadButton.IsEnabled = false;

					_forecastPairRefs.Clear();

					Thread thread = new Thread(ThreadedForecastTableReading) {IsBackground = true};
					thread.Start();
				}
			}
			else
			{
				//закрытие окна
				DialogResult = true;
			}
		}

		private void ThreadedForecastTableReading()
		{
			ButsaManager.Instance.ReadForecastTableLight(ReadForecastProgress, ReadForecastCompleted);
		}

		private void ThreadedTeamsReading()
		{
			List<string> teamsIds = _forecastPairRefs.Select(item => item.HomeTeamId.ToString()).ToList();
			teamsIds.AddRange(_forecastPairRefs.Select(item => item.GuestTeamId.ToString()).ToList());
			//teamsIds = teamsIds.Take(4).ToList();
			ButsaManager.Instance.ReadTeams(teamsIds, ReadTeamsProgress, ReadTeamsCompleted);
		}

		private void ReadForecastProgress(object sender, ProgressEventArgs args)
		{
			LogMessage(String.Format("Чтение таблицы прогноза {0}% - {1}", args.CurrentProgress.ToString("0.0"), args.InfoMessage));
		}

		private void ReadForecastCompleted(object sender, ReadForecastCompletedArgs args)
		{
			_forecastPairRefs = args.ForecastPairs;

			//теперь читаем команды
			Thread thread = new Thread(ThreadedTeamsReading) { IsBackground = true };
			thread.Start();
		}

		private void ReadTeamsProgress(object sender, ProgressEventArgs args)
		{
			LogMessage(String.Format("Чтение команд {0}% - {1}", args.CurrentProgress.ToString("0.0"), args.InfoMessage));
		}

		private void ReadTeamsCompleted(object sender, ReadTeamsCompletedArgs args)
		{
			_teams = args.Teams;
			LoadButton.Dispatcher.Invoke(new Action(() => 
			{ 
				LoadButton.IsEnabled = true;
				LoadButton.Content = "Закрыть";
			}));

			//создаём объект снимка
			MakeSnapshot();

		}

		private void MakeSnapshot()
		{
			if (Dispatcher.CheckAccess())
			{
				Snapshot = new Snapshot
				           	{
				           		ResultsApplied = false,
				           		ForecastPairs = _forecastPairRefs,
				           		Teams = _teams,
				           		SnapshotDate = DateTime.Now,
				           		SnapshotName = SnapshotNameTextBox.Text.Trim()
				           	};
			}
			else
			{
				Dispatcher.Invoke(new Action(MakeSnapshot), new object[] { });
			}
		}

		private void LogMessage(string message)
		{
			if (LogTextBox.Dispatcher.CheckAccess())
			{
				LogTextBox.Text = message + "\r\n" + LogTextBox.Text;
			}
			else
			{
				LogTextBox.Dispatcher.Invoke(new Action(() => LogMessage(message)), new object[] { });
			}
		}
	}
}
